package co.gov.medellin.ssti.sub.web.action;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.springframework.beans.factory.annotation.Autowired;

import co.gov.medellin.ssti.sub.common.excepcion.SUBException;
import co.gov.medellin.ssti.sub.model.dao.exception.DAOException;
import co.gov.medellin.ssti.sub.model.service.BeneficiarioService;
import co.gov.medellin.ssti.sub.model.vo.BeneficiarioVO;
import co.gov.medellin.ssti.sub.paoyer.administration.exception.AdministrationUserException;
import co.gov.medellin.ssti.sub.paoyer.administration.model.vo.UserVO;
import co.gov.medellin.ssti.sub.paoyer.administration.util.AccessControl;
import co.gov.medellin.ssti.sub.paoyer.common.exception.CommonUserException;
import co.gov.medellin.ssti.sub.paoyer.common.exception.UserException;
import co.gov.medellin.ssti.sub.web.form.GuardarBeneficiarioForm;

public class GuardarBeneficiarioAction extends Action {
	@Autowired
	BeneficiarioService beneficiarioServiceImpl;

	/**
	 * This is the main action called from the Struts framework.
	 * 
	 * @param mapping
	 *            The ActionMapping used to select this instance.
	 * @param form
	 *            The optional ActionForm bean for this request.
	 * @param request
	 *            The HTTP Request we are processing.
	 * @param response
	 *            The HTTP Response we are processing.
	 * @return
	 * @throws java.io.IOException
	 * @throws javax.servlet.ServletException
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {

		ActionMessages messages = new ActionMessages();
		try {
			AccessControl access = new AccessControl();
			access.validateAccess(mapping, request, response);

			BeneficiarioVO objBeneVO = new BeneficiarioVO();
			GuardarBeneficiarioForm guardarForm = (GuardarBeneficiarioForm) form;
			HttpSession session = request.getSession();
			session.removeAttribute("CodeBeneSelected");

			Collection cGrupoFamiliar = null;
			Collection cBenef = null;

			// String strDocumento = guardarForm.getNumeroDocumento();
			// String strTipoDocumento = guardarForm.getTipoDocumento();
			String strOption = (String) session.getAttribute("Option");

			objBeneVO.setTipoDocumento(guardarForm.getTipoDocumento());
			objBeneVO.setNumeroDocumento(guardarForm.getNumeroDocumento());
			objBeneVO.setNombre1(guardarForm.getPrimer_nombre());
			objBeneVO.setNombre2(guardarForm.getSegundo_nombre());
			objBeneVO.setPrimerApellido(guardarForm.getPrimerApellido());
			objBeneVO.setSegundoApellido(guardarForm.getSegundoApellido());
			objBeneVO.setHechoVictimizante(guardarForm
					.getCodeHechoVictimizante());

			if (guardarForm.getFechaNacimiento() != null
					&& guardarForm.getFechaNacimiento().length() > 0) {
				objBeneVO.setFechaNacimiento(guardarForm.getFechaNacimiento());
			} else {
				objBeneVO.setFechaNacimiento(null);
			}

			objBeneVO.setSexo(guardarForm.getSexo());
			objBeneVO.setTelefono(guardarForm.getTelefono());
			objBeneVO.setDirDescriptiva(guardarForm.getDirDescriptiva());
			objBeneVO.setDirEncasillada(guardarForm.getDirEncasillada());
			objBeneVO.setVflComuna(guardarForm.getVflComuna());
			objBeneVO.setCobama(guardarForm.getCobama());
			objBeneVO.setCodeBarrio(guardarForm.getCodeBarrio());
			objBeneVO.setCodeZona(guardarForm.getCodeZona());
			objBeneVO.setEtnia(guardarForm.getEtnia());
			objBeneVO.setMail(guardarForm.getMail());
			// Para la auditoria de registros
			UserVO user = (UserVO) session.getAttribute("userInfo");
			String terminalAddress = request.getRemoteAddr();
			objBeneVO.setCreationUser(user.getName());
			objBeneVO.setUpdateUser(user.getName());
			objBeneVO.setCreationTerminal("WEB=" + terminalAddress);
			objBeneVO.setUpdateTerminal("WEB=" + terminalAddress);
			Calendar c = Calendar.getInstance();
			SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
			objBeneVO.setUpdateDate(dateFormat.format(c.getTime()));
			objBeneVO.setCreationDate(dateFormat.format(c.getTime()));

			String insert[] = new String[2];
			try {
				// Proceso para determinar si el beneficiario esta en la base de
				// datos del SUB

				cBenef = beneficiarioServiceImpl.findBeneficiarioByCriteria(
						objBeneVO, "ingresarBeneficiario");
				// Fin del proceso
				if (cBenef != null && cBenef.size() == 0) {
					insert = beneficiarioServiceImpl.insert(objBeneVO);
				}
			} catch (DAOException e) {
				insert[0] = "false";
				SUBException.logDebugError("", e);
			}

			if (cBenef != null && cBenef.size() == 0) {
				if (insert[0].equals("true")) {
					session.removeAttribute("beneficiarios");
					ArrayList<BeneficiarioVO> beneList = new ArrayList<BeneficiarioVO>();
					Collection<BeneficiarioVO> beneficiarios = null;
					session.setAttribute("msg", "");
					objBeneVO.setCode(new Long(insert[1]));
					beneList.add(objBeneVO);
					beneficiarios = beneList;
					session.setAttribute("beneficiarios", beneficiarios);
					session.setAttribute("CodeBeneSelected", insert[1]);
					if (strOption != null && !strOption.equals("")) {
						session.setAttribute(
								"msgOk",
								"El beneficiario se registro correctamente al sistema. Ahora puede asignarlo al grupo familiar");
						return mapping.findForward("VerGrupo");
					} else {
						cGrupoFamiliar = (Collection) session
								.getAttribute("InsertGrupoFamiliar");
						if (cGrupoFamiliar != null
								&& cGrupoFamiliar.size() != 0) {
							return mapping.findForward("InsertGrupoFamiliar");
						} else {
							return mapping.findForward("success");
						}

					}

				} else {
					session.setAttribute("fail",
							"No se pudo ingresar el registro..");
					return mapping.findForward("failInsert");
				}
			} else {
				request.setAttribute("failMsg",
						"El beneficiario ya esta registrado en el SUB...");
				return mapping.findForward("failInsert");
			}

		} catch (UserException ue) {
			messages.add("msgWarn", new ActionMessage("loginForm.message."
					+ ue.getExceptionVO().getId()));
			saveMessages(request, messages);
			if (ue.getExceptionVO().getId() == AdministrationUserException.ENDED_SESSION) {
				response.sendRedirect(request.getContextPath() + "/index.jsp");
			} else if (ue.getExceptionVO().getId() == CommonUserException.NOT_ALLOWED_RESOURCE) {
				response.sendRedirect(request.getContextPath()
						+ "/admin/tile/invalidatedResource.jsp");
			} else {
				return mapping.getInputForward();
			}

		}

		return mapping.findForward("success");

	}
}